import bpy
from bpy_extras import view3d_utils
import bgl
import blf
import os

bl_info = {
    "name": "Simple Line Drawing",
    "author": "lwm",
    "location": "View3D > Tools > Drawing",
    "version": (1, 0, 0),
    "blender": (2, 7, 9),
    "description": "Minimal add-on for line drawing"
}

#color and font
rgb_label = (1, 0.8, 0.1, 1.0)
font_size = 16
font_id = 0

def gl_pts(context, v):
    return view3d_utils.location_3d_to_region_2d(context.region, context.space_data.region_3d, v)

def draw_text(v, display_text, fsize, font_id=0):
    if v:
        blf.size(font_id, font_size, 72)
        blf.position(font_id, v[0], v[1], 0)
        blf.draw(font_id, display_text)

def draw_line(v1, v2):
    if v1 and v2:
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex2f(*v1)
        bgl.glVertex2f(*v2)
        bgl.glEnd()

def draw_main(context):
    scene = context.scene

    rgb_line = (0.173, 0.545, 1.0, 1.0)
    rgb_label = (1.0, 0.8, 0.1, 1.0)
    fsize = 16

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glLineWidth(1)
    bgl.glColor4f(*rgb_line)

    
    objNum = len(bpy.data.meshes)
    if objNum >= 2:
        meshes = [i for i in bpy.data.objects if i.type == 'MESH']
        mainObj = meshes[0]
        for obj in meshes[1:]:
            v1 = gl_pts(context, mainObj.matrix_world.to_translation())
            v2 = gl_pts(context, obj.matrix_world.to_translation())
            print('drawing {} {}'.format(v1,v2))
            draw_line(v1, v2) 

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

class glrun(bpy.types.Operator):
    bl_idname = 'glinfo.glrun'
    bl_label = 'Display lines'
    bl_description = 'Display lines between objs'

    _handle = None

    @staticmethod
    def handle_add(context):
        if glrun._handle is None:
            glrun._handle = bpy.types.SpaceView3D.draw_handler_add(draw_main, (context,), 'WINDOW', 'POST_PIXEL')
            context.window_manager.run_opengl = True
            
    @staticmethod
    def handle_remove(context):
        if glrun._handle is not None:
            bpy.types.SpaceView3D.draw_handler_remove(glrun._handle, 'WINDOW')
            glrun._handle = None 
            context.window_manager.run_opengl = False

    def execute(self, context):
        if context.area.type == 'VIEW_3D':
            if context.window_manager.run_opengl == False:
                self.handle_add(context)
                context.area.tag_redraw()
            else:
                self.handle_remove(context)
                context.area.tag_redraw()
            return {'FINISHED'}
        else:
            print('3D Viewport is not found')
            return {'CANCELLED'}

class glpanel(bpy.types.Panel):
    bl_idname = 'glinfo.glpanel'
    bl_label = 'Display Object'
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'ShowLines'

    def draw(self, context):
        lay = self.layout
        scn = context.scene

        box = lay.box()

        if context.window_manager.run_opengl is False:
            icon = 'PLAY'
            txt = 'Display'
        else:
            icon = 'PAUSE'
            txt = 'Hide'
        box.operator('glinfo.glrun', text=txt, icon=icon)

    @classmethod
    def register(cls):
        print('register {}'.format(cls.bl_idname))

    @classmethod
    def unregister(cls):
        print('unregister {}'.format(cls.bl_idname))



def register():
    bpy.utils.register_class(glrun)
    bpy.utils.register_class(glpanel)
    wm = bpy.types.WindowManager
    wm.run_opengl = bpy.props.BoolProperty(default=False)
    print('{} register complete'.format(bl_info.get('name')))

def unregister():
    bpy.utils.unregister_class(glpanel)
    bpy.utils.unregister_class(glrun)
    wm = bpy.types.WindowManager
    if 'run_opengl' in wm:
        del wm[p]
    print('{} unregister complete'.format(bl_info.get('name')))

if __name__ == "__main__":
    try:
        unregister()
    except Exception as e:
        print(e)
        pass
    finally:
        register()
